package com.weiqiao.report.distributior.rest;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mingsoft.util.StringUtil;
import com.weiqiao.report.distributior.Service.DistributionStatisticsService;
import com.weiqiao.report.distributior.domain.DistributionStatisticsEntity;
import com.weiqiao.report.distributior.domain.ReturnDistributionStatisticsEntity;
import com.weiqiao.report.util.MemberTypeUtil;
import com.weiqiao.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.weiqiao.aop.log.Log;

@RestController
@RequestMapping("api")
public class DistributionStatisticsController {

    /**
    * 业务层
    */
    @Autowired
    private DistributionStatisticsService distributionStatisticsService;


    /**
    * 获取列表
    * @param request
    * @return
    */
    @Log("查询DistributionStatistics")
    @GetMapping(value = "/distribution-statistics")
    public ResponseEntity getList(HttpServletRequest request) {
        int company_id = SecurityUtils.getCompanyId();
        //组装查询条件
        Bson filter = this.getDistributionStatisticsParameterDocument(request);
        String page = request.getParameter("page");
        String limit = request.getParameter("size");
        int pageInt = StringUtil.isInteger(page)? Integer.parseInt(page) : 0;
        int limitInt = StringUtil.isInteger(limit)? Integer.parseInt(limit): 20;
        ReturnDistributionStatisticsEntity entity = 
                distributionStatisticsService.statisticsResultList(company_id, filter, pageInt, limitInt);
        return new ResponseEntity(PageUtil.toPage(entity.getList(), entity.getCount()), HttpStatus.OK);
    }


    /**
    * 封装列表查询条件
    * @param request
    * @return
    */
    private Bson getDistributionStatisticsParameterDocument(HttpServletRequest request) {

        Document doc = new Document();
        String time = request.getParameter("time");
        if (!StringUtil.isBlank(time) && time.split("~").length > 1) {
            doc.append("create_date", new Document("$gte", "" + DateUtil.getTime(time.split("~")[0])).append("$lte",
                    "" + DateUtil.getTime(time.split("~")[1])));
        }
        String name = request.getParameter("name");
        if (!StringUtils.isBlank(name)) {
            List<Document> List = new ArrayList<>();
            List.add(new Document("phone", new Document("$regex", name)));
            List.add(new Document("nick_name", new Document("$regex", name)));
            List.add(new Document("name", new Document("$regex", name)));
            doc.append("$or", List);
        }
        String inviteId = request.getParameter("invite_id");
        if (!StringUtils.isBlank(inviteId)) {
            doc.append("invite_id", Integer.parseInt(inviteId));
        }
        String memberType = request.getParameter("member_type");
        if (!StringUtils.isBlank(memberType)) {
            doc.append("member_type", Integer.parseInt(memberType));
        }
        return doc;
    }

    /**
     * （分销员列表）导出查询、勾选
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/export-distribution-statistics")
    public void exportDistributionStatistics(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int company_id = SecurityUtils.getCompanyId();
        //组装查询条件
        Bson filter = this.getDistributionStatisticsParameterDocument(request);
        ReturnDistributionStatisticsEntity entity =
                distributionStatisticsService.statisticsResultList(company_id, filter, 0, 200);
        FileUtil.downloadExcel(this.exportList(entity), response);
    }


    /**
     * 将要导出的数据集合
     * @param entity
     * @return
     */
    public List<Map<String, Object>> exportList(ReturnDistributionStatisticsEntity entity) {
        List<Map<String, Object>> export = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(entity.getList())) {
            for (DistributionStatisticsEntity info: entity.getList()) {
                export.add(this.ExcelContent(info));
            }
        }
        return export;
    }

    /**
     * 导出内容组装
     * @param entity
     * @return
     */
    public Map<String, Object> ExcelContent(DistributionStatisticsEntity entity) {
        Map map = new HashMap();
        map.put("用户编码", entity.getUser_id());
        map.put("手机号码", entity.getPhone());
        map.put("微信昵称", entity.getNick_name());
        map.put("姓名", entity.getName());
        map.put("邀请人", entity.getInvite_id());
        map.put("等级角色", MemberTypeUtil.getMemberType(entity.getMember_type()));
        map.put("下级推广数", entity.getLower_level_invitation());
        map.put("自己推广数", entity.getOwn_invitation());
        map.put("自己申请数", entity.getOwn_apply());
        map.put("推广收益", entity.getInvitation_income());
        map.put("当前余额", entity.getScore());
        return map;
    }
}
